package com.zhb.cloud.core.distribute.redisson.lock;

import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @ClassName: RedisClientFactory
 * @author: zhb
 * @date: 2017年8月4日 上午10:41:02
 * @Description: redisson 分布式锁的实现
 *
 */
public class RedisClientFactory {

	private static final Logger LOG = LoggerFactory.getLogger(RedisClientFactory.class);

	/**
	 * Redisson clients 缓存
	 */
	private static final ConcurrentHashMap<String, RedissonClient> sRedissonCache = new ConcurrentHashMap<String, RedissonClient>();

	static {
		// 关闭所有已存在的 redisson clients
		Runtime.getRuntime().addShutdownHook(new Thread() {
			@Override
			public void run() {
				closeRedissonClients();
			}
		});
	}

	/**
	 * RedissonClient creation method
	 * 
	 * @param host
	 * @param port
	 * @param timeout
	 * @param password
	 * @return
	 */
	public synchronized static RedissonClient createRedisson(String host, Integer port, int timeout, String password) {
		RedissonClient client = sRedissonCache.get(host + ":" + port);
		if (client != null && !client.isShutdown()) {
			return client;
		}
		// 够建配置
		Config config = new Config();
		SingleServerConfig singleServerConfig = config.useSingleServer();
		singleServerConfig.setAddress(host + ":" + port);
		singleServerConfig.setTimeout(timeout);
		if (!StringUtils.isBlank(password)) {
			singleServerConfig.setPassword(password);
		}
		// 创建客户端
		client = Redisson.create(config);
		sRedissonCache.put(host + ":" + port, client);
		return client;
	}

	/**
	 * 关闭 redisson client
	 */
	private static synchronized void closeRedissonClients() {
		for (Entry<String, RedissonClient> entry : sRedissonCache.entrySet()) {
			entry.getValue().shutdown();
			sRedissonCache.remove(entry.getKey());
		}
		LOG.info("redisson client destroy succeed.");
	}
}
